<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable placeholder="商品名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.id" clearable placeholder="商品id" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.parent_id" clearable placeholder="分类id" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <!-- <el-select v-model="listQuery.status" placeholder="状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.a" :value="item.b" />
      </el-select> -->
      <!-- <el-input v-model="listQuery.title" placeholder="商品名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-select v-model="listQuery.type" placeholder="状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button> -->
      <!-- <el-select v-model="listQuery.status" placeholder="状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.a" :value="item.b" />
      </el-select> -->
      <!-- <el-select v-model="listQuery.type" placeholder="状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />
      </el-select> -->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <!-- <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        Export
      </el-button> -->
      <!-- <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox> -->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类ID" width="90px">
        <template slot-scope="{row}">
          <span>{{ row.parent_id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="200px">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="跳转地址" >
        <template slot-scope="{row}">
          <span>{{ row.path_url||'-' }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="入驻/加盟费" width="120px">
        <template slot-scope="{row}">
          <span>{{ row.franchise_fee }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="是否展示" width="90px">
        <template slot-scope="{row}">
          <span>{{ row.is_show }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="是否热门" width="90px">
        <template slot-scope="{row}">
          <span>{{ row.show_index }}</span>
        </template>
      </el-table-column> -->


      <el-table-column label="图标" width="120px">
        <template slot-scope="{row}">
          <!-- <span>{{ row.name }}</span> -->
          <img v-if="row.icon_url" :src="baseimgurl + row.icon_url" alt="" style="width:50px;height:50px;">
        </template>
      </el-table-column>
      <el-table-column label="图片" >
        <template slot-scope="{row}">
          <!-- <span>{{ row.name }}</span> -->
          <img v-for="el in row.banner_list" :src="baseimgurl+el" alt="" style="width:50px;height:50px;margin-left:5px;">
        </template>
      </el-table-column>
      <el-table-column label="描述" >
        <template slot-scope="{row}">
          <span>{{ row.front_desc||'-' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="排序" >
        <template slot-scope="{row}">
          <span>{{ row.sort||'-' }}</span>
        </template>
      </el-table-column>

      <!-- <el-table-column label="简介">
        <template slot-scope="{row}">
          <span>{{ row.front_name }}</span>
        </template>
      </el-table-column> -->

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <!-- <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ row.status | statusFilter }}
          </el-button> -->
          <el-button v-if="row.status!='published'" size="mini" type="success" @click="handleUpdate(row)">
            编辑
          </el-button>

          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">

        <el-form-item label="分类名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="简介" >
          <el-input v-model="temp.front_desc" />
        </el-form-item>

        <el-form-item label="上级分类">
          <el-select clearable v-model="temp.parent_id" class="filter-item" placeholder="请选择上级分类">
            <el-option v-for="(item, idx) in catypelist" :key="idx" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="跳转地址" >
          <el-input v-model="temp.path_url" />
        </el-form-item>
        <el-form-item label="排序" >
          <el-input type="Number" v-model="temp.sort" />
        </el-form-item>
        <el-form-item label="是否展示">
          <el-switch
            v-model="temp.is_show"
            active-color="#13ce66"
            inactive-color="#ff4949">
            </el-switch>
        </el-form-item>
        <!-- <el-form-item label="是否热门">
          <el-switch
            v-model="temp.show_index"
            active-color="#13ce66"
            inactive-color="#ff4949">
            </el-switch>
        </el-form-item> -->
        <el-form-item label="分类图标">
          <el-upload
            action=""
            accept="image/jpeg,image/png"
            :on-change="onUploadxqimg"
            :auto-upload="false"
            :show-file-list="false"
          >
            <el-button slot="trigger" size="small" type="primary">选取</el-button>
            <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button> -->
            <div slot="tip" class="el-upload__tip">
              <p v-if="!temp.icon_url">只能上传jpg/png文件，且不能超过1m</p>
              <img v-if="imgurl" style="width:100px;height:100px;" :src="imgurl" alt="">
              <img v-if="temp.icon_url" style="width:100px;border:1px solid green;height:100px;" :src="baseimgurl+temp.icon_url" alt="">
              <div class="">
                <el-button v-if="pic_files" size="small" @click="uploadimgsend" type="primary">确认上传</el-button>
              </div>
            </div>

          </el-upload>
        </el-form-item>

        <el-form-item label="分类图片集">
          <el-upload
            ref="$upload"
            action=""
            accept="image/jpeg,image/png"
            :on-change="onUploadxqimg2"
            :on-remove="handleRemove"
            :auto-upload="false"
            :show-file-list="true"
          >
            <el-button slot="trigger" size="small" type="primary">选取</el-button>
            <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button> -->
            <div slot="tip" class="el-upload__tip">
              <p v-if="!temp.banner_list.length">只能上传jpg/png文件，且单张不能超过1m</p>
              <!-- <img v-if="imgurl" style="width:150px;height:150px;" :src="imgurl" alt=""> -->
              <img v-for =" ele in banner_list" style="width:100px;height:100px;margin-right:5px;" :src="ele" alt="">
              <!-- <img v-if="temp.banner_list" style="width:150px;border:1px solid #f00;" :src="baseimgurl+temp.wap_banner_url" alt=""> -->

              <img v-for="el in temp.banner_list" v-if="!banner_list.length" style="width:100px;border:1px solid green;height:100px;margin-right:5px" :src="baseimgurl+el" alt="">
              <div class="">
                <el-button v-if="pic_filesList.length" size="small" @click="uploadimgsend2" type="primary">确认上传</el-button>
              </div>
            </div>

          </el-upload>
        </el-form-item>


        <!-- <el-form-item label="分类">
          <el-select v-model="temp.type" class="filter-item" placeholder="">
            <el-option v-for="item in catypelist" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
    <!-- <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog> -->
  </div>
</template>

<script>
import {fetchStorenav,uploadImg, fetchStorenav_create,fetchStorenav_del,fetchStorecatype ,fetchStorenavall} from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

// const calendarTypeOptions = [
//   { key: 'CN', display_name: 'China' },
//   { key: 'US', display_name: 'USA' },
//   { key: 'JP', display_name: 'Japan' },
//   { key: 'EU', display_name: 'Eurozone' }
// ]
let _catypelist = [];
// arr to obj, such as { CN : "China", US : "USA" }
// const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
//   acc[cur.key] = cur.display_name
//   return acc
// }, {})

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    // parseTime(a,b) {
    //   console.log(a,b)
    //   return ''
    // },
    catypefn(type){
      let str = '-';
      _catypelist.forEach(el => {
        if(el.id == type) str = el.title;
      })
      // console.log(_catypelist)
      return str;
    },
    statusFilter(status) {
      return status === '1' ? '禁用' : '开启'
      // const statusMap = {
      //   published: 'success',
      //   draft: 'info',
      //   deleted: 'danger'
      // }
      // return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      baseimgurl: '',
      imgurl: '',
      banner_list: [],
      pic_files: '',
      pic_filesList: [],
      listLoading: false,
      textMap: {
        update: '编辑分类',
        create: '添加分类'
      },
      dialogFormVisible: false,


      tableKey: 0,
      list: null,
      total: 0,
      catypelist:[],
      listQuery: {
        page: 1,
        limit: 20,
        id:  undefined,
        name: undefined,
        parent_id: undefined,
        status: undefined,
        sort: '+id'
      },
      isupload: false,
      importanceOptions: [1, 2, 3],
      calendarTypeOptions: [{a: '展示',b:1},{a: '隐藏',b:0}],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['1', '0'],
      showReviewer: false,
      temp: {
        banner_list:[],
        icon_url: '',
        level: 0,
        viplevel: 0,
        name: '',
        front_desc: '',
        sort: 0,
        path_url: '',
        is_show: true,
        parent_id: '',
      },

      dialogStatus: '',

      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '商品名称为必填项！', trigger: 'blur' }],
        front_name: [{ required: true, message: '必填项！', trigger: 'blur' }],
        front_desc: [{ required: true, message: '必填项！', trigger: 'blur' }],
        keywords: [{ required: true, message: '必填项！', trigger: 'blur' }],
        // wap_banner_url: [{ required: true, message: '必填项！', trigger: 'blur' }],
        // subtile: [{ required: true, message: '商品名称为必填项！', trigger: 'blur' }],
        // price: [{ required: true, message: '商品名称为必填项！', trigger: 'blur' }],
        // timedata: [{ required: true, message: '商品名称为必填项！', trigger: 'blur' }],
        // picimg: [{ required: true, message: '商品名称为必填项！', trigger: 'blur' }],
      },
      downloadLoading: false
    }
  },
  // updata(){
  //
  // },
  created() {
    this.getcatype();
    this.getList()
  },
  methods: {
    handlePreview(file) {
      console.log(file);
    },
    handleRemove(file, fileList) {
      if(this.temp.banner_list.length) return false;
      let _this = this;
      this.banner_list = [];
      this.pic_filesList = fileList;
      fileList.forEach(file => {
          var reader = new FileReader();
          reader.readAsDataURL(file.raw);
          reader.onload = function(e){
            // console.log(e.target)
            _this.banner_list.push(this.result);
          }
        })

     console.log(file, fileList);
   },
    onUploadxqimg2(file) {
      const _this = this
      const isIMAGE = (file.raw.type === 'image/jpeg' || file.raw.type === 'image/png');
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isIMAGE) {
        this.$message.error('只能上传jpg/png图片!');
        return false;
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 1MB!');
        return false;
      }
      this.pic_filesList.push(file);
      var reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = function(e){
        _this.banner_list.push(this.result);
          // console.log(this.result)//图片的base64数据
      }
    },
    onUploadxqimg(file) {
      const _this = this
      console.log(file)
      const isIMAGE = (file.raw.type === 'image/jpeg' || file.raw.type === 'image/png');
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (!isIMAGE) {
        this.$message.error('只能上传jpg/png图片!');
        return false;
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 1MB!');
        return false;
      }
      this.pic_files = file;
      var reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = function(e){
        // console.log(e.target)
        _this.imgurl = this.result;
          // console.log(this.result)//图片的base64数据
      }
    },
    uploadimgsend() {
      const  _this = this;
      var formFile = new FormData()
      formFile.append('file', this.pic_files.raw)
      formFile.append('fileName', 'oneFenlei')
      this.isupload = true
      uploadImg(formFile).then(response => {
        // _this.temp.xqimg = 'http://localhost:8092/public'+response.data;
        _this.temp.icon_url = response.fileUrl
        _this.isupload = false
        _this.pic_files = null;
        _this.imgurl = '';
      })
      return false
    },
    uploadimgsend2() {
      const  _this = this;

      let fileList = [];
      _this.temp.banner_list = [];
      this.pic_filesList.forEach(el => {
        // fileList.push(el.raw)
        var formFile = new FormData();
        formFile.append('file', el.raw)
        formFile.append('fileName', 'oneFenlei')
        this.isupload = true
        uploadImg(formFile).then(response => {
          // _this.temp.xqimg = 'http://localhost:8092/public'+response.data;
          _this.temp.banner_list.push(response.fileUrl)
          _this.pic_filesList = [];
          _this.banner_list = [];
        })
      })
      console.log(fileList, this.pic_filesList)

      return false
    },
    getcatype(){
      this.listLoading = true

      fetchStorenav( this.listQuery).then(response => {
        // this.temp.type = response.data[0].title;
        this.catypelist = response;
        // _catypelist = this.catypelist;

        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getList() {
      this.listLoading = true
      fetchStorecatype(this.listQuery).then(response => {
        this.list = response.data.map(item => {
          console.log(item,'===')
          item['is_show'] = Boolean(item['is_show'])
          item['banner_list'] = item['banner_list']&&item['banner_list'].split(',');
          return item;
        });
        this.total = response.count

        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        status: '1'
      }
    },
    handleCreate() {
      // this.resetTemp()
      // this.$refs['$upload'].clearFiles();
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.temp['title']='';
      this.imgurl = '';
      this.banner_list = [];
      this.pic_files = '';
      this.pic_filesList = []
      this.temp= {
        banner_list:[],
        icon_url: '',
        level: 0,
        viplevel: 0,
        name: '',
        front_desc: '',
        sort: 0,
        path_url: '',
        is_show: true,
        parent_id: '',
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs['$upload'].clearFiles();
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.listLoading = true;
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin';
          // console.log(this.temp)
            const tempData = Object.assign({}, this.temp)
            tempData['is_show'] = Number(tempData['is_show']);
            tempData['banner_list'] = tempData['banner_list']&&tempData['banner_list'].join();
          fetchStorenav_create(tempData).then(() => {
            // this.list.unshift(this.temp)
            // this.listLoading = false;

            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            this.temp = {
              banner_list:[],
              icon_url: '',
              name: '',
              level: 0,
              viplevel: 0,
              path_url: '',
              sort: 0,
              front_desc: '',
              is_show: true,
              parent_id: '',
            };
            this.getList()
          },()=>{
            this.listLoading = false;
          })
        }
      })
    },
    handleUpdate(row) {

      //
      this.dialogStatus = 'update'
      this.temp = row
      this.dialogFormVisible = true;
      this.imgurl = '';
      this.banner_list = [];
      this.pic_files = '';
      this.pic_filesList = []
      this.$nextTick(() => {
        this.$refs['$upload'].clearFiles();
      })
      // return false;
      // updateStorecatype(datas).then(() => {
      //   const index = this.list.findIndex(v => v.id === this.temp.id)
      //
      //   this.$notify({
      //     title: 'Success',
      //     message: 'Update Successfully',
      //     type: 'success',
      //     duration: 2000
      //   })
      // })
      // this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      // this.dialogStatus = 'update'
      // this.dialogFormVisible = true
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
      // this.updateData();
    },
    updateData() {
      this.listLoading = true;
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData['is_show'] = Number(tempData['is_show']);
          tempData['banner_list'] = tempData['banner_list']&&tempData['banner_list'].join();
          fetchStorenav_create(tempData).then(() => {
            this.dialogFormVisible = false;
            this.temp = {
              banner_list:[],
              icon_url: '',
              name: '',
              front_desc: '',
              is_show: true,
              path_url: '',
              sort: 0,
              viplevel: 0,
              level: 0,
              parent_id: '',
            };
            this.$notify({
              title: 'Success',
              message: '更新成功！',
              type: 'success',
              duration: 2000
            });
            this.getList()
          })
        }else{
          this.listLoading = false;
        }
      })
    },
    handleDelete(row, index) {
      this.listLoading = true;
      this.$confirm(`确定要删除分类: ${row.name} ？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        fetchStorenav_del({id: row.id}).then((res) => {
          console.log(res);
          this.$notify({
            title: 'Success',
            message: '删除分类成功！',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })

      }).catch(() => {
        this.listLoading = false;
      });

      return false;
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
